import Taro from '@tarojs/taro'
import { ROLE_STATE, SPCIES_TYPE } from "../contorl/src/constant"
import { getCanvas } from "../contorl/ctx";
import { getCloudUrl } from '../contorl/src/utils'


/**
 * 初始化图片
 */
export const loadingImage = async (myCanvas) => {
  const canvas: any = myCanvas || getCanvas()
  if (canvas) {
    const list: Promise<unknown>[] = []
    /**
     * 创建任务
     */
    const createdTask = img => {
      return new Promise((resolve, reject) => {
        img.onload = () => {
          resolve(img)
        }
        img.onerror = () => {
          reject()
        }
      })
    }
    /**
     * 角色
     */
    Object.values(ROLE_STATE).forEach(item => {
      const img = canvas.createImage()
      img.src = item.src
      list.push(createdTask(img))
    })
    /**
     * 物体类型
     */
    Object.values(SPCIES_TYPE).forEach(item => {
      const img = canvas.createImage()
      img.src = item.src
      list.push(createdTask(img))
    })
    /**
     * 吃到金币帧
     */
    const EXPLO_FRAME_COUNT = 11
    for (let i = 0; i < EXPLO_FRAME_COUNT; i++) {
      const img = canvas.createImage()
      img.src = getCloudUrl(`images/${i + 1}-removebg-preview.png`)
      list.push(createdTask(img))
    }
    /**
     * 吃到pua
     */
    for (let i = 1; i < 4; i++) {
      const img = canvas.createImage()
      img.src = getCloudUrl(`images/pua-${i}.png`)
      list.push(createdTask(img))
    }
    /**
     * 并发加载图片
     */
    await Promise.allSettled(list)
  } else {
    throw new Error('图片加载失败, 未获取到canvas实例')
  }
}